package 基础语法.网络编程;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TCP_接受并反馈 {
     public static void main(String[] args) {
        Thread senThread = new Thread() {
            @Override
            public void run() {
                try {
                    sendData();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        Thread receiveThread = new Thread() {
            @Override
            public void run() {
                try {
                    receiveData();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        //receiveThread.setPriority(10000);
        receiveThread.start();// 必须先启动
        
        //senThread.setPriority(100000);
        senThread.start();
       

    }

    static void sendData() throws Exception {
        // 1.
        // 在创建对象是会尝试连接服务器，如果连接不上，代码报错
        Socket socket = new Socket("127.0.0.1", 8080);

        // 2.从连接中获取输出流
        OutputStream os = socket.getOutputStream();// SocketOutputStream
        os.write("你好".getBytes());//发送数据
        socket.shutdownOutput();//告知对方结束发送，必须要加，不然服务端bufferedReader.readLine()不会结束，一直卡折 

        System.out.println("等待反馈");
        InputStream is=socket.getInputStream();
        InputStreamReader ir=new InputStreamReader(is);
        BufferedReader bufferedReader=new BufferedReader(ir);
        System.out.println(bufferedReader.readLine());
        
        
        os.close();
        bufferedReader.close();
        socket.close();

    }

    static void receiveData() throws Exception {
        // 1.
        ServerSocket serverSocket = new ServerSocket(8080);// 端口保持与发送端一致
        // 2.监听客户端的连接
        Socket socket = serverSocket.accept();

        // 3.从连接通道中获取输入流读取数据
        InputStream inputStream = socket.getInputStream();// SocketInputStream

        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);// 转换流
     
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);// 包装流
       

        System.out.println("接收到内容："+bufferedReader.readLine());


        OutputStream os=socket.getOutputStream();
        os.write("我已接收到数据".getBytes());//发送反馈

        socket.close();
        bufferedReader.close();
        os.close();

    }

}
